import 'package:flutter/material.dart';
import 'package:hxdj/common/base_page/my_loading_page.dart';
import 'package:hxdj/common/components/banner.dart';
import 'package:hxdj/common/components/my_clip_rect.dart';
import 'package:hxdj/common/components/my_picture_preview.dart';
import 'package:hxdj/common/components/my_statistic.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/env_config/env.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/common/routers/navigator.dart';
import 'package:hxdj/home/order/order_create_viewmodel.dart';
import 'package:hxdj/home/project_details/project_details_page.dart';
import 'package:hxdj/home/technician_detail.dart/technician_detail_viewmodel.dart';
import 'package:hxdj/message/message_page/message_viewmodel.dart';
import 'package:hxdj/message/rongcloud/rc_chat/rc_chat_page.dart';
import 'package:flutter_unionad/flutter_unionad.dart';
import 'package:provider/provider.dart';

//技师详情
class TechnicianDetailPage extends StatefulWidget {
  static String routeName = "/TechnicianDetail";

  final String tId;

  const TechnicianDetailPage({super.key, required this.tId});

  @override
  State<TechnicianDetailPage> createState() => _TechnicianDetailPageState();
}

class _TechnicianDetailPageState extends State<TechnicianDetailPage> {
  late TechnicianDetailsViewModel viewModel;

  @override
  void initState() {
    super.initState();
  }

  @override
  void activate() {
    OrderCreateViewModel orderCreateViewModel = Provider.of<OrderCreateViewModel>(context, listen: false);
    orderCreateViewModel.technicianModel = null;
    super.activate();
  }

  @override
  dispose() {
    super.dispose();
  }

  //详情
  _buildTechnicianDetail() {
    return Container(
        margin: EdgeInsets.all(15.w),
        child: MyBorder(
            decoration: MyBorder.defaultDecoration,
            radius: 10,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 15.h),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  //金额
                  Row(
                    children: [
                      MyText(viewModel.detailModel.name ?? "",
                          fontSize: 15.sp, fontWeight: FontWeight.bold, color: MyColours.text),
                      const Spacer(),
                      Padding(
                          padding: EdgeInsets.only(right: 5.w),
                          child: const MyImage(imageName: "ic_distance", width: 10, height: 12.5)),
                      MyText(viewModel.detailModel.distance ?? "",
                          fontSize: 11.sp, fontWeight: FontWeight.bold, color: MyColours.textGray),
                    ],
                  ),

                  Container(
                    padding: EdgeInsets.only(top: 10.h, bottom: 2.h),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Expanded(
                          child: MyText(viewModel.detailModel.desc ?? "",
                              maxLines: 3, fontSize: 12.sp, color: MyColours.text),
                        ),
                        MyTapWidget(
                            onTap: () {
                              //去咨询 ldjt12592
                              NavigatorUtils.pushParams(
                                      context, "${RCChatPage.routeName}?targetId=${viewModel.detailModel.imUser}")
                                  .then((value) {
                                MessageViewModel viewModel = Provider.of<MessageViewModel>(context, listen: false);
                                viewModel.requetsData();
                              });
                            },
                            child: Container(
                              margin: EdgeInsets.only(left: 33.w),
                              decoration: BoxDecoration(
                                color: MyColours.appMain,
                                borderRadius: BorderRadius.circular(20),
                              ),
                              padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 7.h),
                              alignment: Alignment.center,
                              child: Text("咨询",
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 12.sp,
                                    fontWeight: FontWeight.w600,
                                  )),
                            )),
                      ],
                    ),
                  ),
                ],
              ),
            )));
  }

  _buildHeaderService() {
    return Container(
        margin: EdgeInsets.only(top: 5.h, bottom: 10.h, left: 28.w),
        child: Row(
          children: [
            Padding(
              padding: EdgeInsets.only(right: 5.w),
              child: const MyImage(imageName: "ic_recommend_project", width: 18),
            ),
            Column(
              children: [
                MyText("提供服务", textStyle: MyTextStyles.textBlackBold16),
                MyBorder(
                    color: MyColours.appMain,
                    backgroundColor: MyColours.appMain,
                    radius: 1.5,
                    child: SizedBox(
                      width: 25.w,
                      height: 3,
                    ))
              ],
            )
          ],
        ));
  }

  //服务 list
  _buildServiceList() {
    return Column(
      children: viewModel.projectDataList.map((e) {
        return ProjectDetailItem(context: context, projectModel: e, detailModel: viewModel.detailModel);
      }).toList(),
    );
  }

  //穿山甲广告
  _buildAd() {
    //获取屏幕的宽
    double screenWidth = MediaQuery.of(context).size.width;

    return SafeArea(
      child: MyBorder(
          decoration: MyBorder.defaultDecoration,
          radius: 10,
          child: Container(
            child: //个性化模板信息流广告
                FlutterUnionad.nativeAdView(
              //android 信息流广告id 必填
              androidCodeId: Env.getInstance()!.csjAndroidCodeId,
              //ios banner广告id 必填
              iosCodeId: Env.getInstance()!.csjIosCodeId,
              //是否支持 DeepLink 选填
              supportDeepLink: true,
              // 期望view 宽度 dp 必填
              expressViewWidth: screenWidth - 30.w,
              //期望view高度 dp 必填
              expressViewHeight: 0,
              mIsExpress: false,
              //控制下载APP前是否弹出二次确认弹窗
              downloadType: FlutterUnionadDownLoadType.DOWNLOAD_TYPE_POPUP,
              //用于标注此次的广告请求用途为预加载（当做缓存）还是实时加载，
              adLoadType: FlutterUnionadLoadType.LOAD,
              callBack: FlutterUnionadNativeCallBack(
                onShow: () {
                  debugPrint("信息流广告显示");
                },
                onFail: (error) {
                  debugPrint("信息流广告失败 $error");
                },
                onDislike: (message) {
                  debugPrint("信息流广告不感兴趣 $message");
                },
                onClick: () {
                  debugPrint("信息流广告点击");
                },
              ),
            ),
          )),
    );
  }

  _buildBody() {
    switch (viewModel.state) {
      case ViewState.loading:
        return const Scaffold(appBar: MyAppBar(title: "技师详情"), body: MyLoadingWidget());
      default:
        List<String>? imgs = viewModel.detailModel.imgs?.split(",") ?? [""];
        imgs.removeWhere((element) => (element.endsWith("mp4") || element.endsWith("MOV")));
        return Scaffold(
            appBar: const MyAppBar(title: "技师详情"),
            body: SingleChildScrollView(
              child: Stack(
                children: [
                  Column(
                    children: [
                      MyBannerView(imgs, height: 334.h, select: (int index) {
                        NavigatorUtils.pushParams(context, MyPicturePreviewPage.routeName,
                            params: {"index": index, "imgUrls": imgs, "heroTag": imgs[index]});
                      }),
                      _buildTechnicianDetail(),
                      _buildHeaderService(),
                      _buildServiceList(),
                      _buildAd(),
                    ],
                  ),
                ],
              ),
            ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return BasePage<TechnicianDetailsViewModel>(
        onModelReady: (model) {
          // 页面初始化完成后的回调
          viewModel = model;

          viewModel.requestData(tId: widget.tId);
        },
        viewModel: TechnicianDetailsViewModel(),
        builder: (BuildContext context, TechnicianDetailsViewModel? model, Widget? child) {
          return _buildBody();
        });
  }
}

class ProjectDetailItem extends StatelessWidget {
  const ProjectDetailItem({
    super.key,
    required this.context,
    required this.projectModel,
    required this.detailModel,
  });

  final BuildContext context;
  final TechnicianProjectDetailModel projectModel;
  final TechnicianDetailModel detailModel;

  @override
  Widget build(BuildContext context) {
    return MyTapWidget(
      onTap: () {
        //项目详情
        NavigatorUtils.pushParams(
            context, '${PackageDetailPage.routeName}?tId=${detailModel.tId}&gId=${projectModel.goodsId}');
      },
      child: Container(
        margin: EdgeInsets.fromLTRB(16.w, 0, 16.w, 15.h),
        child: MyBorder(
          radius: 11.w,
          decoration: MyBorder.defaultDecoration,
          child: Row(
            children: [
              MyClipRect(imageUrl: projectModel.coverImg ?? "", width: 110.w, radius: 11.w, height: 110.w),
              Expanded(
                child: Container(
                  padding: EdgeInsets.only(left: 10.w, top: 5.h),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      MyText(projectModel.title ?? "",
                          fontSize: 14.sp, fontWeight: FontWeight.bold, color: MyColours.text),
                      Container(
                          padding: EdgeInsets.only(top: 5.h, bottom: 5.h),
                          child: MyText("${projectModel.serviceDurationStr ?? ""} | ${projectModel.titleDesc ?? ""}",
                              fontSize: 12.sp, color: MyColours.textGray)),

                      // 套餐价格
                      Container(
                        child: MyStatisticViewModel(
                          statistic: num.parse(projectModel.price ?? "0"),
                          statisticTS:
                              TextStyle(fontSize: 18.sp, color: MyColours.colorFF4414, fontWeight: FontWeight.w700),
                          withName: '¥' " ",
                          withNameTS:
                              TextStyle(fontSize: 15.sp, color: MyColours.colorFF4414, fontWeight: FontWeight.w700),
                          statisticDecimalTS: TextStyle(color: MyColours.colorFF4414, fontSize: 15.sp),
                          prefix: '',
                          suffix: '',
                          isCurrency: false,
                          toStringAsFixed: 0,
                        ).toRichText,
                      ),

                      Row(
                        children: [
                          MyText(
                            "¥${projectModel.goodsDiscountPrice}",
                            fontSize: 14.sp,
                            color: MyColours.color73736EB,
                            fontWeight: FontWeight.bold,
                          ),
                          Container(
                              margin: EdgeInsets.only(left: 6.w),
                              color: MyColours.colorE7C8A6,
                              padding: EdgeInsets.symmetric(horizontal: 2.w, vertical: 2.w),
                              alignment: Alignment.center,
                              child: Text("会员价",
                                  style: TextStyle(
                                    color: MyColours.color8E6447,
                                    fontSize: 8.sp,
                                    fontWeight: FontWeight.w700,
                                  ))),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(right: 10.w),
                child: Column(
                  children: [
                    MyTapWidget(
                        onTap: () {
                          //项目详情
                          NavigatorUtils.pushParams(context,
                              '${PackageDetailPage.routeName}?tId=${detailModel.tId}&gId=${projectModel.goodsId}');
                        },
                        child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                          Container(
                            decoration: BoxDecoration(
                              color: MyColours.appMain,
                              borderRadius: BorderRadius.circular(15),
                            ),
                            padding: EdgeInsets.symmetric(horizontal: 10.5.w, vertical: 4.5.h),
                            alignment: Alignment.center,
                            child: Text("去预约",
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 12.sp,
                                  fontWeight: FontWeight.w700,
                                )),
                          ),
                        ])),
                    Padding(
                      padding: EdgeInsets.only(top: 5.h),
                      child: MyText("30天${projectModel.salesStr}",
                          fontSize: 9.sp, fontWeight: FontWeight.bold, color: MyColours.textGrayA),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
